<template>
	<view class="container">
		<view class="swiper">
			<u-swiper :list="swiperList" imgMode="aspectFit" height="640rpx" radius="0" @click="handleClickSwiper"></u-swiper>
<!--			<view class="swiper-count">1/5</view>-->
		</view>
		<view class="goods_box">
			<view class="goods_info">
				<view class="top_price">
					<view class="price_box">
						<view class="present_price">
							<text class="default">￥</text>
							<text>{{ productInfo.price }}</text>
							<text class="default">/件</text>
						</view>
						<view class="original_price">￥{{ productInfo.underlined_price }}/件</view>
					</view>
					<view class="leave_count">
						库存：{{ stock }}件
					</view>
				</view>
				<view class="center_title">
					{{ productInfo.name }}
				</view>
				<view class="product_box">
					<view class="product_info">
						品质保障
					</view>
					<view class="product_after">基地优选 售后无忧</view>
				</view>
			</view>

            <!-- 服务项 -->
			<view class="wight_serve">
				<view class="weight_box" v-for="(item, i) in services" :key="i">
					<view class="weight">{{ item.title }}</view>
					<view class="weight_info">{{ item.desc }}</view>
				</view>
			</view>

			<view class="specifications" @tap="" v-if="1 == 2">
				<view class="specifications_title">选规格</view>
				<u-icon name="arrow-right" color="#666666" size="16"></u-icon>
			</view>

			<view class="user_commment">
				<view class="comment_box">
					<view class="comment_top_box">
						<view class="comment_top">用户评价</view>
						<view class="comment_count">（{{ reviewNumber }}）</view>
					</view>
					<view class="comment_all_box" @tap="goAllComments">
						<view class="comment_all">查看全部</view>
						<u-icon name="arrow-right" color="#666666" size="12"></u-icon>
					</view>
				</view>
				<view class="comment-list" v-if="latestReview?.user">
					<view class="comment-item">
						<view class="left">
<!--							<u-avatar size="60rpx" v-if="latestReview?.user" :src="checkAndFixUrl(latestReview?.user?.avatar)"></u-avatar>-->
<!--							<u-avatar size="60rpx" v-else src="/static/images/avatar.png"></u-avatar>-->
							<u-avatar size="60rpx" :src="getServerStatic('/static/images/avatar.png')"></u-avatar>
						</view>
						<view class="right">
							<view class="nickname-box">
								<view class="nickname">{{ latestReview?.user?.name ?? '' }}</view>
								<view class="date">{{ latestReview.created_at }}</view>
							</view>
							<view class="stars">
								<u-rate inactiveIcon="star-fill" readonly inactiveColor="#DCDEE0" activeColor="#FBA808"
									gutter="6rpx" v-model="latestReview.score"></u-rate>
							</view>

							<view class="comment-box">
								{{ latestReview.content }}
							</view>
							<view class="img-list" v-if="latestReview?.images">
								<view class="img-item" v-for="(value ,index) in latestReview.images" :key="index">
									<u-image radius="10rpx" width="110rpx" height="110rpx"
										:src="checkAndFixUrl(value)"></u-image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 富文本 -->
		<view class="parse-wrap">
			<view class="parse-box">
				<u-parse :content="content"></u-parse>
			</view>
		</view>

		<!-- 底部按钮组 -->
		<view class="bottom-btns">
			<uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="iconClick"
				@buttonClick="buttonClick" />
		</view>
	</view>

    <!-- 选择规格弹窗组件 -->
    <SelectSku ref="selectSkuRef"
               :productAttrs="productAttrs"
               :productSkus="productSkus"
               :productInfo="productInfo"
               @confirmSku="confirmSku"
    >
    </SelectSku>


    <!-- 客服电话 -->
    <u-action-sheet round="30rpx" :show="showPhone" :actions="actions" title="" description=""
                    @close="showPhone = false" @select="callConfirm">
    </u-action-sheet>

</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow} from '@dcloudio/uni-app'
    import {useSystemStore} from "@/store";
    import {getLatestReview, getProductDetail} from "@/api/product";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    import SelectSku from '@/components/SelectSku'
    import {storeCart} from "@/api/cart";
    // 系统
    const systemStore = useSystemStore()

    const goBack = () => {
        uni.navigateBack()
    }

    // 商品ID
    const productId = ref(0)

    onLoad((evt) => {
        console.log('商品详情', evt)
        if (!evt?.product_id) {
            uni.showToast({
                mask: true,
                title: '参数错误!',
                icon: 'none'
            })
            setTimeout(() => {
                goBack()
            },500)
        }
        productId.value = evt.product_id

        handleGetProductInfo()
        handleGetLatestReview()

    })

    // 商品属性
    const productAttrs = ref([])
    // 商品规格
    const productSkus = ref([])
    // 商品信息
    const productInfo = ref({})

    // 服务项
    const services = ref([])

    const reviewNumber = ref(0)

    const stock = ref(0)

    // 获取商品详情.
    const handleGetProductInfo = async () => {
        uni.showLoading({
            title: '加载中'
        });

        const {code, data} = await getProductDetail({product_id: productId.value})
        uni.hideLoading();

        if (code === 1) {
            productInfo.value = data?.product ?? {}
            content.value = data?.product?.detail ?? ''
            productAttrs.value = data?.product?.attrs ?? []
            productSkus.value = data?.product?.skus ?? []
            services.value = data?.services ?? []
            reviewNumber.value = data?.reviews ?? 0
            stock.value = data?.stock ?? 0
            // 图片
            swiperList.value = data?.product?.images.map(item => {
                return checkAndFixUrl(item)
            }) ?? []

            console.log('商品属性', productAttrs.value)
            console.log('商品SKU', productSkus.value)
            console.log('商品图片', data?.product?.images)
            console.log('商品信息', data)

        } else {
            goBack()
        }
    }

    const latestReview = ref(null)
    // 最新评价
    const handleGetLatestReview = async () => {
        const {code, data} = await getLatestReview({product_id: productId.value})
        if (code == 1) {
            latestReview.value = data
        }
        console.log('评价',data)
    }

    // 放大图片
    const handleClickSwiper = (index) => {
        uni.previewImage({
            current: index,
            urls: swiperList.value
        });
    }

    const selectSkuRef = ref(null)

    // 选择规格
    const handleSelectAttr = () => {
        selectSkuRef.value.open()
    }

    // 选择完成
    const confirmSku = (result) => {
        console.log(result)
        console.log('选择的sku', result.sku.attr_name)
        // 判断方式
        if (actionType.value === 0) {
            handleAddToCart(result.sku.id, result.quantity)
        } else {
            console.log('直接购买')
            uni.navigateTo({
                url: `/mine/drug-store/confirm?type=single&sku_id=${result.sku.id}&quantity=${result.quantity}`
            })
        }
    }

    const handleAddToCart = async (sku_id, quantity) => {
        // 加入购物车
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await storeCart({sku_id: sku_id, quantity: quantity })
        uni.hideLoading();

        if (code === 1) {
            uni.showToast({
                mask: true,
                title: '已添加!',
                icon: 'success'
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: '/mine/drug-store/car'
                })
            }, 800)
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }

	// 显示弹窗
	const isPayment = ref(false)
	// 底部按钮配置
	const options = ref([{
		icon: 'headphones',
		text: '客服'
	}, {
		icon: 'cart',
		text: '购物车',
	}])
	const buttonGroup = ref([{
			text: '加入购物车',
			backgroundColor: '#97B3FF',
			color: '#fff'
		},
		{
			text: '立即购买',
			backgroundColor: '#4975EC',
			color: '#fff'
		}
	])

    // 0 加入购物车 1 立即购买
    const actionType = ref(0)

    // 点击按钮
	const buttonClick = e => {
		// 0 加入购物车 1 立即购买
		console.log(e.index)
        actionType.value = e.index
        // 状态是否为立即购买
        isPayment.value = e.index === 1
        handleSelectAttr()
	}

	const iconClick = e => {
		// 0 客服 1 购物车
		console.log(e.index);
		if (e.index == 0) {
            showPhone.value = true
		} else if (e.index == 1) {
			uni.navigateTo({
				url: '/mine/drug-store/car'
			})
		}
	}

    // 客服
    const showPhone = ref(false)
    const actions = ref([{
            name: `一键拨打：${systemStore.customer}`,
            isCall: true
        },
        {
            name: '取消',
            isCall: false
        },
    ])

    // 拨打电话
    const callConfirm = e => {
        console.log(e);
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.customer
            })
        }
    }

	const swiperList = ref([])

    // 详情
	const content = ref('<p></p>')

	// 全部评价
	const goAllComments = () => {
		uni.navigateTo({
			url: `/mine/drug-store/comments?product_id=${productId.value}`
		})
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: 250rpx;
	}

	.swiper {
		position: relative;

		.swiper-count {
			position: absolute;
			right: 40rpx;
			bottom: 20rpx;
			background: rgba(0, 0, 0, 0.2);
			@include center(80rpx, 40rpx);
			color: #FFFFFF;
			font-size: 24rpx;
			border-radius: 20rpx;
			z-index: 99;
		}
	}

	.goods_box {
		padding: 0 26rpx;
		margin-top: 24rpx;

		.goods_info {
			padding: 24rpx 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx 20rpx 20rpx 20rpx;

			.top_price {
				@include between();

				.price_box {
					display: flex;
					align-items: center;

					.present_price {
						font-size: 44rpx;
						color: #F55726;

						.default {
							font-size: 24rpx;
						}
					}

					.original_price {
						margin-left: 10rpx;
						font-size: 24rpx;
						color: #CCCCCC;
						text-decoration: line-through;
					}
				}

				.leave_count {

					font-size: 24rpx;
					color: #CCCCCC;
				}
			}

			.center_title {

				margin-top: 20rpx;
				font-size: 36rpx;
				color: #333333;
				line-height: 50rpx;
			}

			.product_box {
				display: flex;
				align-items: center;
				margin-top: 20rpx;

				.product_info {
					@include center(106rpx, 39rpx);
					background: #516DDB;
					border-radius: 3rpx;
					font-size: 22rpx;
					color: #FFFFFF;
				}

				.product_after {
					font-size: 22rpx;
					color: #666666;
					margin-left: 16rpx;
				}
			}
		}


		.wight_serve {
			margin-top: 20rpx;
			padding: 30rpx 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			@include between(100%, 150rpx);
			flex-direction: column;
			align-items: flex-start;

			.weight_box {
				@include start();

				.weight {
					font-size: 24rpx;
					color: #CCCCCC;
				}

				.weight_info {
					margin-left: 20rpx;
					font-size: 24rpx;
					color: #333333;
				}
			}
		}

		.specifications {
			margin-top: 20rpx;
			padding: 30rpx 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			@include between();

			.specifications_title {

				font-size: 24rpx;
				color: #333333;
			}
		}

		.user_commment {
			margin-top: 20rpx;
			padding: 30rpx 20rpx 1rpx;
			background: #FFFFFF;
			border-radius: 20rpx;

			.comment_box {
				@include between(100%);
				border-bottom: 1rpx solid #F2F2F2;
				padding-bottom: 30rpx;
				margin-bottom: 24rpx;

				.comment_top_box {
					@include start();

					.comment_top {

						font-size: 26rpx;
						color: #333333;
					}

					.comment_count {
						font-size: 24rpx;
						color: #CCCCCC;
					}
				}

				.comment_all_box {
					display: flex;
					align-items: center;

					.comment_all {

						font-size: 22rpx;
						color: #666666;
						margin-right: 10rpx;
					}
				}
			}

			.comment-list {
				.comment-item {
					@include between(100%);
					align-items: flex-start;

					.right {
						flex: 1;
						margin-left: 20rpx;

						.nickname-box {
							@include between(100%);

							.nickname {
								color: #333333;
								font-size: 24rpx;
							}

							.date {
								font-size: 22rpx;
								color: #CCCCCC;
							}
						}

						.stars {
							margin-top: 10rpx;
						}

						.comment-box {
							margin-top: 24rpx;
							font-size: 24rpx;
							line-height: 32rpx;
							color: #666666;
							margin-bottom: 28rpx;
						}

						.img-list {
							display: flex;
							align-items: center;
							flex-wrap: wrap;

							.img-item {
								margin-right: 21rpx;
								margin-bottom: 28rpx;
							}
						}
					}
				}
			}
		}
	}

	.parse-wrap {
		margin-top: 20rpx;
		padding: 26rpx;
		background: #FFFFFF;
		width: 100%;
	}
	.sku-pop {
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		padding: 40rpx 40rpx 52rpx;
		.title {
			font-size: 32rpx;
			color: #222222;
			text-align: center;
			margin-bottom: 50rpx;
		}
		.content-box {
			@include between(100%, 100%);
			margin-bottom: 70rpx;
			.right {
				flex: 1;
				margin-left: 22rpx;
				@include between(100%, 170rpx);
				flex-direction: column;
				align-items: flex-start;
				// padding: 10rpx 0;
				color: #000000;
				font-size: 30rpx;
				.com-title {
					color: #F55726;
					font-size: 28rpx;
					.price {
						font-weight: bold;
						font-size: 50rpx;
					}
				}
			}
		}
		.sku-select-box {
			margin-bottom: 40rpx;
			.sku-tip {
				color: #333333;
				font-size: 30rpx;
				margin-bottom: 30rpx;
			}
			.sku-list {
				@include start();
				flex-wrap: wrap;
				.sku-item {
					padding: 20rpx 26rpx;
					background: #EBEBEB;
					border-radius: 20rpx;
					color: #333333;
					font-size: 30rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					border: 1rpx solid #EBEBEB;
				}
				.active {
					background: #E8EBF6;
					border: 1rpx solid #516DDB;
				}
			}
		}
		.pay-number {
			margin-top: 50rpx;
			@include between(100%);
		}
		.confirm-btn {
			margin-top: 60rpx;
		}
	}

	.bottom-btns {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 999;
		padding-top: 16rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		background: #FFFFFF;
		padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
		box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0, 0, 0, 0.1);
	}
</style>
